import axios from 'axios'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'

const requset = axios.create({
  baseURL: 'http://127.0.0.1:8080',
  timeout: 10000
})

// 请求拦截器
requset.interceptors.request.use((config) => {
  const userStore = useUserStore()
  const token = userStore.getToken()
  if (token) {
    config.headers.Authorization = token
  }

  return config
})
// 响应拦截器
requset.interceptors.response.use(
  (res) => {
    //业务错误
    if (res.data.code !== 200) {
      ElMessage.error(res.data.msg || '服务器异常')
      return Promise.reject(new Error(res.data.msg || '服务器异常'))
    }
    return res.data
  },
  (err) => {
    // 401 权限不够
    if (err.response?.status === 401) {
      ElMessage.error(err.response.data.msg || '权限不够')
      router.push('/login')
      return
    }
    ElMessage.error(err.response.data?.msg)
    return Promise.reject(new Error(err.response.data?.msg))
  }
)

export default requset
